#include <head.h>

#define SERVER_IP "192.168.70.37"
#define SERVER_PORT 5000
#define BUFFER_SIZE 1024

void *read_thread(void *arg)
{
    int fd = *(int *)arg;
    char buf[BUFFER_SIZE];
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        if (0 >= read(fd, buf, sizeof(buf)))
        {
            close(fd);
            return NULL;
        }
        printf("接收到的数据是:%s\n", buf);
    }
}

int main(int argc, char const *argv[])
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        perror("socket");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    addr.sin_port = htons(SERVER_PORT);
    addr.sin_family = AF_INET;

    if (-1 == connect(fd, (struct sockaddr *)&addr, sizeof(addr)))
    {
        perror("connect");
        close(fd);
        return -1;
    }

    pthread_t tid;
    pthread_create(&tid, NULL, read_thread, &fd);
    pthread_detach(tid);

    char buf[BUFFER_SIZE];
    while (1)
    {
        printf("输入信息:");
        scanf("%s", buf);
        getchar();
        write(fd, buf, strlen(buf));
    }

    close(fd);
    return 0;
}